﻿using System.Windows.Input;

namespace SimpleTool.Base
{
    class EasyCommand(Action<object?> obj, Func<bool> flag) : ICommand
    {
        //  组件绑定时
        //  WPF框架会自动做这些事情：
        //  1. 按钮订阅命令的CanExecuteChanged事件
        //  2. 定期检查CanExecute()返回值来更新按钮的IsEnabled状态
        //  3. 当用户点击时，自动调用Execute()方法

        private readonly Action<object?> execute = obj;

        private readonly Func<bool> canexecute = flag;

        //  状态判断逻辑  
        public bool CanExecute(object? func)
        {
            if (canexecute == null) return true;
            return canexecute();
        }

        //  执行逻辑
        public void Execute(object? obj)
        {
            execute(obj);
        }

        //  状态变化通知机制
        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }
    }
}
